package Stackdemo;

import java.util.Stack;
//逆波兰式求值
public class Rpn {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(String x:tokens){
            //如果是数字字符串
            if(!isOperation(x)){
                //将数字字符串转为数字压入栈
                stack.push(Integer.parseInt(x));
            }else{
                //如果是运算符字符串，将顶两个数据出栈运算
                int num1 = stack.pop();
                int num2 = stack.pop();
                switch (x){
                    case "+":
                        stack.push(num2+num1);
                        break;
                    case "-":
                        stack.push(num2-num1);
                        break;
                    case "*":
                        stack.push(num2*num1);
                        break;
                    case "/":
                        stack.push(num2/num1);
                        break;
                }
            }
        }
        return stack.pop();
    }
    //判断是否是运算符
    private boolean isOperation(String s) {
        if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")) {
            return true;
        }
        return false;
    }
}
